#!/usr/bin/env ruby

require File.dirname(__FILE__) + '/../config/boot'

JUGGERNAUT_PID_FILE = "tmp/pids/juggernaut.pid"

def kill_juggernaut
  return unless File.exist?(JUGGERNAUT_PID_FILE)
  system("kill #{File.read(JUGGERNAUT_PID_FILE).strip}")
  system("rm #{JUGGERNAUT_PID_FILE}")
end

def juggernaut_config_file
  return "config/juggernaut.yml" if File.exist?("config/juggernaut.yml")
  "config/juggernaut/#{ENV['RAILS_ENV'] || "development"}.yml"
end

def start_juggernaut
  kill_juggernaut
  system("juggernaut -d -P #{JUGGERNAUT_PID_FILE} -c #{juggernaut_config_file} -l log/juggernaut.log")
end

def start_autospec
  fork do
    require File.dirname(__FILE__) + '/../config/boot'
    require File.dirname(__FILE__) + '/../config/environment'
    require File.join(Rio::LIB_ROOT, "autospec")

    AutoSpec.run
  end
end

def start_server
  system("script/server #{ARGV}")
end

start_juggernaut
start_autospec

if (ARGV.to_s.match(/--no-mongrel/))
  begin
    loop do
    end
  rescue Interrupt
    puts
  end  
else
  start_server
end

kill_juggernaut

